package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.vo.ServiceItemAuditVO;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        //参数判断
        //防止非法上架
        ServiceItem newItem = new ServiceItem();
        newItem.setCreateTime(new Date());
        newItem.setName(serviceItem.getName());
        newItem.setOriginalPrice(serviceItem.getOriginalPrice());
        newItem.setDiscountPrice(serviceItem.getDiscountPrice());
        newItem.setCarPackage(serviceItem.getCarPackage());
        newItem.setServiceCatalog(serviceItem.getServiceCatalog());
        newItem.setInfo(serviceItem.getInfo());

        serviceItem.setCreateTime(new Date());
        //判端数据是否为套餐
        if (serviceItem.getCarPackage().equals(ServiceItem.CARPACKAGE_YES)) {
            //套餐：初始化
            newItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            //非套餐：无需审核
            newItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItemMapper.insert(newItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        //根据id获取数据,获取其中的字段用来判断
        ServiceItem oldItem = this.get(serviceItem.getId());
        //审核中或者上架状态抛出异常
        if (ServiceItem.AUDITSTATUS_AUDITING.equals(oldItem.getAuditStatus()) || ServiceItem.SALESTATUS_ON.equals(oldItem.getSaleStatus())) {
            throw new BusinessException("非法操作");
        }
        //判断数据如果是套餐，将审核状态改为初始化状态
        if (ServiceItem.CARPACKAGE_YES.equals(oldItem.getCarPackage())) {
            //将审核状态改为初始化
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }
        serviceItem.setCarPackage(oldItem.getCarPackage());
        serviceItem.setCreateTime(oldItem.getCreateTime());
        //更新数据
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

   @Override
    public boolean checkNameExsit(String name) {
        return serviceItemMapper.selectByName(name) != null;
    }

    @Override
    public void saleOn(Long id) {
        //根据id查询服务单项
        ServiceItem serviceItem = this.get(id);
        //判断数据如果已经上架抛出异常
        if (ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("已经上架了");
        }

        //判断如果是套餐并且审核状态是非审核通过，抛出异常
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) && !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("非法操作");
        }

        //修改审核通过的产品需要修改其上架状态
        //修改数据
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }


    @Override
    public void saleOff(Long id) {
        //根据id获取数据
        ServiceItem serviceItem = this.get(id);
        //若是数据已经下架抛出异常
        if (ServiceItem.SALESTATUS_OFF.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("已经下架了");
        }
        //修改项目为下架状态
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    //发起审核
    @Transactional
    public void startAudit(ServiceItemAuditVO vo) {
        //查询数据
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(vo.getId());
        //合理化判断
        //非套餐，抛异常
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            throw  new BusinessException("非法操作");
        }
        //审核中，审核通过抛异常
        if (ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()) || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())) {
            throw new  BusinessException("非法操作");
        }
        //创建CarPackageAudit发起审核的数据
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setInfo(vo.getInfo());
        carPackageAudit.setServiceItemId(vo.getId());
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo());
        carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice());
        carPackageAudit.setCreateTime(new Date());
        carPackageAudit.setBpmninfoId(vo.getBpmnInfoId());
        carPackageAudit.setAuditorId(vo.getDirector());//店长
        carPackageAudit.setCreator(ShiroUtils.getUser().getUserName());
        //插入操作
        carPackageAuditMapper.insert(carPackageAudit);
        //设置流程实例的参数
        HashMap<String, Object> map = new HashMap<>();
        //设置三个参数：审核人，财务审核人不一定有，需要进行判空
        map.put("director",vo.getDirector());
        if (vo.getFinance()!=null) {
            map.put("finance",vo.getFinance());
        }
        map.put("discountPrice",serviceItem.getDiscountPrice().longValue());

        //开启流程实例,并绑定业务标识
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(vo.getBpmnInfoId());
        //开始实例：(参数1：)流程定义key  (参数2：)绑定业务标识，一般为发起审核的对象的id，business Key是string类型，(参数3：)设置的流程变量
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(), carPackageAudit.getId().toString(), map);
        //为CarPackageAudit设置流程实例的id，更新数据
        carPackageAudit.setInstanceId(instance.getId());
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
        //修改服务单向的状态为审核中
        serviceItemMapper.changeStatus(vo.getId(),ServiceItem.AUDITSTATUS_AUDITING);
    }
}
